package cn.gp.filter;


import cn.gp.common.R;
import cn.gp.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginCheckFilter
 * @Description 登陆校验过滤器
 * @Author He_Guoping
 * @Date 2023/5/25 18:10
 * @Version 1.0
 */
@Log4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 1.登陆请求需放行
        String url = req.getRequestURI();
        if(url.contains("login")) {
            log.info("登陆请求需放行");
            filterChain.doFilter(req, resp);
            return;
        }

        // 2.token不存在
        String token = req.getHeader("token");
        if(!StringUtils.hasLength(token)) {
            log.info("token不存在");
            resp.getWriter().write(JSONObject.toJSONString(R.error("not logged in")));
            return;
        }

        // 3.解析token失败
        try {
            JwtUtils.parseToken(token);
        } catch(Exception e) {
            log.info("解析token失败");
            resp.getWriter().write(JSONObject.toJSONString(R.error("not logged in")));
            return;
        }

        // 4.放行
        log.info("token合法");
        filterChain.doFilter(req, resp);

    }

    @Override
    public void destroy() {

    }
}
